###
  上传指定文件夹到指定服务器
###

_path = require 'path'
_fse = require 'fs-extra'
_fs = require 'fs'
_fstream = require 'fstream'
_tar = require 'tar'
_zlib = require 'zlib'
_http = require 'http'
_request = require 'request'
_url = require 'url'

config = require './config'
TEMPDIR = config.tmpDir
SERVER = config.server
SRCDIR = config.src
DISTDIR = config.dist

ZIPFOLDER = _path.join TEMPDIR, DISTDIR
ZIPFILE = "#{ZIPFOLDER}.tar.gz"

getFormData = (file)->
  attachments:
    value: _fs.createReadStream(file)
    options:
      contentType: 'application/x-gzip'

begin = ->
  #copy Dir To Tmp
  #delete tmp
  tmp = ZIPFOLDER
  #empty tmp directory
  _fse.emptyDirSync(tmp)
  #copy directory
  sourceDir = _path.join process.cwd(), SRCDIR
  _fse.copySync(sourceDir, tmp) if _fs.existsSync(sourceDir)

  #zip and send file
  _fstream.Reader(ZIPFOLDER)
    .pipe(_tar.Pack())
    .pipe(_zlib.Gzip())
    .pipe(_fstream.Writer(ZIPFILE))
    .on('close', ->
      console.log _url.resolve(SERVER.url, SERVER.upload)
      _request
        .post(_url.resolve(SERVER.url, SERVER.upload), formData: getFormData(ZIPFILE))
        .on('respone', ()->
          _fse.emptyDirSync(tmp)
      )
    )


begin()

